import dayjs from "dayjs";
import userAvatar from "@/assets/header.png";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { user_list } from "@/api/user";
import { type Ref, reactive, ref, onMounted, h, toRaw, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection, hideTextAtIndex } from "@pureadmin/utils";

import { useUserStoreHook } from "@/store/modules/user";

export function useRole(PerformanceInfoRef: Ref) {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_single_see: false, // 查看组员业绩
  })

  const dataList = ref([]);
  const loading = ref(true);
  const form = reactive({
    // 左侧部门树的id
    department_belong: useUserStoreHook()?.department_belong,
    not_me: 1,
    page: 1,
    pagesize: 15
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 15,
    currentPage: 1,
    background: true
  });
  const columns = reactive<TableColumnList>([
    {
      label: "头像",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.avatar || userAvatar}
          preview-src-list={Array.of(row.avatar || userAvatar)}
          class="w-[24px] h-[24px] rounded-full align-middle"
        />
      ),
      width: 90
    },
    {
      label: "用户名",
      prop: "account",
      minWidth: 180
    },
    {
      label: "昵称",
      prop: "nickname",
      minWidth: 180
    },
    {
      label: "手机号",
      prop: "phone",
      minWidth: 140,
      formatter: ({ phone }) => hideTextAtIndex(phone, { start: 3, end: 6 })
    },
    {
      label: "创建时间",
      prop: "time",
      formatter: ({ created_at }) => dayjs.unix(created_at).format("YYYY-MM-DD HH:mm:ss"),
      minWidth: 180
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      minWidth: 106
    }
  ]);

  // 查看业绩详情
  function lookInfo(row) {
    PerformanceInfoRef.value.openDrawer(row);
  }

  function handleSizeChange(val: number) {
    form.pagesize = val;
    pagination.pageSize = val
    onSearch(); // 刷新表格数据
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    pagination.currentPage = val
    onSearch(); // 刷新表格数据
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    const result = await user_list(toRaw(form));

    dataList.value = result.data;
    pagination.total = result.count;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  onMounted(() => {
    onSearch();

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/teamManagement/performance/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/teamManagement/performance/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);

      // performance_tab
      if (homeDataObj.performance_tab) {
        // single
        if (homeDataObj.performance_tab.single && homeDataObj.performance_tab.single.length) {
          let permiss = homeDataObj.performance_tab.single.join(',')
          permissions.is_single_see = permiss.includes('see') ? true : false
        }

        let tableRemove = homeDataObj.performance_tab.remove ? homeDataObj.performance_tab.remove.split(',') : []
        for (let i = 0; i < tableRemove.length; i++) {
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].prop == tableRemove[i]) {
              columns.splice(a, 1)
            }
          }
        }
      }
    }
  });

  return {
    permissions,

    loading,
    columns,
    dataList,
    pagination,

    onSearch,
    lookInfo,
    handleOffline,
    handleSizeChange,
    handleCurrentChange
  };
}
